<!--
 * @Description: 生成海报组件【壹点邀请码】
 * @Version: 1.0.0
 * @Autor: hch
 * @Date: 2020-08-07 14:48:41
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-07-31 18:11:35
 * 保存海报按钮和关闭按钮 在html代码中写出来 绑定点击方法然后透明 再用canvas 覆盖
-->
<template>
  <view class="canvas-content" v-show="canvasShow" @click="handleCanvasCancel"
    :style="'width:' + system.w + 'px; height:' + system.h + 'px;text-align:center;'" >
    <!-- 遮罩层 -->
    <view class="canvas-mask"></view>
    <!-- 海报 -->
    <!-- :width="system.w" :height="system.h" 支付宝必须要这样设置宽高才有效果 -->
	<image class="posterUrl" v-if="posterUrl" :src="posterUrl" :style="'width:' + posterBgs.w + 'px; height:' + posterBgs.h + 'px;top:'+(posterBgs.y-20)+'px;left:'+(posterBgs.x)+'px;'" :width="posterBgs.w" :height="posterBgs.h"></image>
	<image class="posterNewImage" v-if="posterNewImage" :src="posterNewImage" style="z-index:608;"></image>
    <canvas  
	  v-if="canvasc"
      class="canvas"
      canvas-id="myCanvas"
      id="myCanvas"
      :style="'width:' + system.w + 'px; height:' + system.h + 'px;'"
      :width="system.w"
      :height="system.h"
    ></canvas>
	
    <view class="button-wrapper">
      <!-- 保存海报按钮 -->
      <!-- #ifndef MP-QQ -->
      <!-- cover-view 标签qq小程序有问题 -->
      <!-- <cover-view class="save-btn" @tap="handleSaveCanvasImage">保存海报</cover-view> -->
      <cover-view class="save-btn cancel-btn" @tap="handleCanvasCancel">关闭</cover-view>
      <!-- #endif -->
      <!-- #ifdef MP-QQ -->
      <!-- <view class="save-btn" @tap="handleSaveCanvasImage">保存海报</view> -->
      <view class="save-btn cancel-btn" @tap="handleCanvasCancel">关闭</view>
      <!-- #endif -->
    </view>
  </view>
</template>

<script>
  import { drawSquarePic, drawTextReturnH, getSystem } from './utils'
  export default {
    data() {
      return {
        system: {},
        canvasShow: false,
		posterUrl:'',
		posterNewImage:'',
		posterTimestamp:0,
		posterBgs:{},
		canvasc:1
      }
    },
    props: {
      posterData: {
        type: Object,
        default: () => {
          return {}
        }
      }, 
    },
    computed: {
      /**
       * @description: 计算海报背景数据
       * @author: hch
       */
      poster() { 
        let data = this.posterData;
        let system = this.system;
		console.log('【海报数据初始化】system 详细信息=> ',data,system);
        let posterBg = {
          url: data.poster.url,
          r: data.poster.r * system.scale,
          w: data.poster.w * system.scale,
          h: data.poster.h * system.scale,
          x: (system.w - data.poster.w * system.scale) / 2,
          y: (system.h - data.poster.h * system.scale) / 2,
          p: data.poster.p * system.scale
        };
		this.posterBgs = posterBg;
		console.log("【海报背景】--原配置数据data.poster=>",data.poster);
        return posterBg
      },
      /**
       * @description: 计算海报标题
       * @param {*}
       * @return {*}
       * @author: hch
       */
      title() {
        let data = this.posterData
        let system = this.system
        let posterTitle = data.title
        posterTitle.x = this.mainImg.x
        posterTitle.y = this.mainImg.y + this.mainImg.h + data.title.mt * system.scale
        return posterTitle
      },
      /**
       * @description: 计算小程序码
       * @param {*}
       * @return {*}
       * @author: hch
       */
      codeImg() {
        let data = this.posterData;
        let system = this.system;
		//TODO 二维码图片配置数据
        let posterCode = {
          url: data.codeImg.url,
          r: data.codeImg.r * system.scale,
          w: data.codeImg.w * system.scale,
          h: data.codeImg.h * system.scale,
          x: (system.w - data.codeImg.w * system.scale) / 2,
          y: data.codeImg.mt * system.scale //y需要加上绘图后文本的y
        }
		console.log("【海报二维码】--原配置数据data.codeImg=>",data.codeImg);
        return posterCode;
      }
    },
    created() {
      this.system = getSystem(); // 获取设备信息
    },
    methods: {
      /**
       * @description: 展示海报
       * @param {type}
       * @return {type}
       * @author: hch
       */
      posterShow() {
        this.canvasShow = true; 
		let posterData = this.posterData;
		let enabledAdmin = posterData.enabledAdmin || 0; //TODO 是否开开启在线后台获取二维码
		let nowStamp = new Date().getTime();
		console.log('【生成海报】现在:'+nowStamp + ";查询后台已开启二维码后端接口服务enabled="+ enabledAdmin,this.posterTimestamp,posterData);
		if(this.posterUrl && this.posterTimestamp>0 && nowStamp-this.posterTimestamp<=5000) {
			return ; //TODO 10秒内暂不重新生成
		}else if(enabledAdmin==1){
			this.onlinePoster() ;	//TODO 后端生成海报
		}else {
			this.creatPoster() ; 	//TODO 前端生成海报
		}
      },
	/**
	 * @description: 生成海报(后台生成)
	 * @author: xch
	 */
	async onlinePoster(){
		let _this = this;
		let _apiUrl = getApp().globalData.url;
		this.posterNewImage='';
		uni.showLoading({  title: '生成海报中...' });
		//TODO 远程调用二维码接口
		this.$api.request({
			url: _apiUrl + '/api/v1/UserInvite/doQrcode?type=1', 
			method: 'POST',
			data: {},
			success: res => {
				uni.hideLoading();
				this.$api.isLoginApi(res);  
				if(res.code==200){ 
					let nowStamp = new Date().getTime();
					console.log('【远程-获取海报】success -> nowTime'+ nowStamp, res);
					//TODO 任务中心的数据接口
					let baseimg = res.data.content || '';
					_this.posterTimestamp= nowStamp;
					_this.posterNewImage = baseimg;
				}else{
					this.$api.msg(res.msg); 
				}
			}
		}); 
	},
	  
  /**
   * @description: 生成海报(绘制格式：背景图片+二维码)
   * @author: xch
   */
    async creatPoster() {
		let _this = this;
		this.posterUrl='';
        uni.showLoading({  title: '生成海报中...' });
        const ctx = uni.createCanvasContext('myCanvas', this);
        this.ctx = ctx;
		//清空之前的海报
        ctx.clearRect(0, 0, this.system.w, this.system.h); 
        ctx.draw(); 
		
        // 根据设备屏幕大小和距离屏幕上下左右距离，及圆角绘制背景
        let poster = this.poster;
        let codeImg = this.codeImg;
		let posterBgUrl = poster.url;
		let codeImgUrl = codeImg.url.replace(/[\r\n]/g, '');
		codeImg.url = codeImgUrl;
		console.log('【生成海报】poster ->背景图片:'+posterBgUrl,poster);
		console.log('【生成海报】codeImg ->二维码图片:'+codeImgUrl ,codeImg);
		
		//绘背景图
        await drawSquarePic(ctx, poster.x, poster.y, poster.w, poster.h, poster.r, posterBgUrl);
		setTimeout(async () => { 
			// 绘制二维码图型
			await drawSquarePic(ctx,codeImg.x,codeImg.y + 10,codeImg.w,codeImg.h,codeImg.r,codeImgUrl);
			//TODO 2秒海报生成时间
			setTimeout(() => {  
				uni.hideLoading();
				uni.canvasToTempFilePath({
				    x: this.poster.x,
				    y: this.poster.y,
				    width: this.poster.w, 	// 画布的宽
				    height: this.poster.h, 	// 画布的高
				    destWidth: this.poster.w * 5,
				    destHeight: this.poster.h * 5,
				    canvasId: 'myCanvas',
				    success(res) {
						uni.hideLoading();
						let nowStamp = new Date().getTime();
						console.log('【生成海报】success -> nowTime'+ nowStamp, res)
						// #ifdef H5
						// h5的时候 
						_this.posterTimestamp= nowStamp;
						_this.posterUrl = res.tempFilePath;
						// _this.handleCanvasCancel()
						// _this.$emit('previewImage', res.tempFilePath)
						// #endif
				    },fail(res) {
						console.log('【生成海报】fail -> res', res)
						uni.showToast({
							title: '保存失败，稍后再试',
							icon: 'none',
							duration: 2000
						});
						uni.hideLoading();
				    }
				  }, this);
			}, 1900);
		},900);
      },
      /**
       * @description: 保存到系统相册
       * @param {type}
       * @return {type}
       * @author: hch
       */
      handleSaveCanvasImage() {
        uni.showLoading({
          title: '保存中...'
        })
        let _this = this
        // 把画布转化成临时文件
        // #ifndef MP-ALIPAY
        // 支付宝小程序外，其他都是用这个方法 canvasToTempFilePath
        uni.canvasToTempFilePath(
          {
            x: this.poster.x,
            y: this.poster.y,
            width: this.poster.w, // 画布的宽
            height: this.poster.h, // 画布的高
            destWidth: this.poster.w * 5,
            destHeight: this.poster.h * 5,
            canvasId: 'myCanvas',
            success(res) {
				
              //保存图片至相册
              // #ifndef H5
              // 除了h5以外的其他端
              uni.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success(res) {
                  uni.hideLoading()
                  uni.showToast({
                    title: '图片保存成功，可以去分享啦~',
                    duration: 2000,
                    icon: 'none'
                  })
                  _this.handleCanvasCancel()
                },
                fail() {
                  uni.showToast({
                    title: '保存失败，稍后再试',
                    duration: 2000,
                    icon: 'none'
                  })
                  uni.hideLoading()
                }
              })
              // #endif

              // #ifdef H5
              // h5的时候
              uni.showToast({
                title: '请长按保存',
                duration: 3000,
                icon: 'none'
              })
              // _this.handleCanvasCancel()
              _this.$emit('previewImage', res.tempFilePath)
              // #endif
            },
            fail(res) {
              console.log('fail -> res', res)
              uni.showToast({
                title: '保存失败，稍后再试',
                duration: 2000,
                icon: 'none'
              })
              uni.hideLoading()
            }
          },
          this
        )
        // #endif
		
        // #ifdef MP-ALIPAY
        // 支付宝小程序条件下 toTempFilePath
        this.ctx.toTempFilePath(
          {
            x: this.poster.x,
            y: this.poster.y,
            width: this.poster.w, // 画布的宽
            height: this.poster.h, // 画布的高
            destWidth: this.poster.w * 5,
            destHeight: this.poster.h * 5,
            success(res) {
              //保存图片至相册
              my.saveImage({
                url: res.apFilePath,
                showActionSheet: true,
                success(res) {
                  uni.hideLoading()
                  uni.showToast({
                    title: '图片保存成功，可以去分享啦~',
                    duration: 2000,
                    icon: 'none'
                  })
                  _this.handleCanvasCancel()
                },
                fail() {
                  uni.showToast({
                    title: '保存失败，稍后再试',
                    duration: 2000,
                    icon: 'none'
                  })
                  uni.hideLoading()
                }
              })
            },
            fail(res) {
              console.log('fail -> res', res)
              uni.showToast({
                title: '保存失败，稍后再试',
                duration: 2000,
                icon: 'none'
              })
              uni.hideLoading()
            }
          },
          this
        )
        // #endif
      },
      /**
       * @description: 取消海报
       * @param {type}
       * @return {type}
       * @author: hch
       */
      handleCanvasCancel() {
        this.canvasShow = false
        // this.$emit('cancel', true)
      }
    }
  }
</script>

<style lang="scss">
  .content {
    height: 100%;
    text-align: center;
  }

  .canvas-content {
    position: fixed;
    top: 0;
	z-index: 500;
    .canvas-mask {
      position: fixed;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      z-index: 509;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
    }
	
	.posterUrl{
		z-index: 510;
		position: fixed;
	}
	.posterNewImage {
		min-width: 285px;
		width: 80%;
		height: 471px;
		/*position: fixed;
		left: 13%;*/
		margin-top: 15%;
		border-radius: 10px;
		box-shadow: 0px 1px 2px #909399;
	}

    .canvas {
      z-index: -100;
	  // visibility: hidden;
	  opacity: 0;
    } 
    .button-wrapper {
      position: fixed;
      // bottom: 160rpx;
	  bottom: 100rpx;
      z-index: 516;
      display: flex;
      width: 100%;
      height: 72rpx;
      justify-content: space-around;
    }

    .save-btn {
      z-index: 516;
      width: 40%;
      height: 100%;
      font-size: 30rpx;
      line-height: 72rpx;
      color: #fff;
      text-align: center;
      background: $base-color;
      border-radius: 45rpx;
      border-radius: 36rpx;
    }

    .cancel-btn {
      color: $base-color;
      background: #fff;
    }

    .canvas-close-btn {
      position: fixed;
      top: 30rpx;
      right: 0;
      z-index: 512;
      width: 60rpx;
      height: 60rpx;
      padding: 20rpx;
    }
  }
</style>
